<template>
    <div class="selection-component">
        <div class="selection-show" @click="toggleDrop">
            <span >{{selections[nowIndex].label}}</span>
            <div class="arrow"></div>
        </div>
        <div class="selection-list" v-if="isDrop">
            <ul style="    display: inline-block;margin: 0 0 0 -40px; width: 100%;">
                <li v-for="(item,index) in selections" :key="index" @click="chooseSelection(index)">{{item.label}}</li>
            </ul>
        </div>
    </div>
</template>
<script>
import {eventBus} from '../../eventBus'
export default {
    props:{
        //父组件传递selections到子组件
        selections:{
            type:Array,
            default:[{
                label: 'test',
                value: 0
            }]
        }
    },
    data(){
        return{
            isDrop:false,
            nowIndex:0
        }
    },
    methods:{
        //下拉切换
        toggleDrop(event){
            event.stopPropagation()
            eventBus.$emit('reset-component') //哪个组件使用，就在那个组件监听$on
            this.isDrop = ! this.isDrop //打开下拉
        },
        chooseSelection(index){
            this.nowIndex = index;
            //this.isDrop = false;//隐藏下拉 ,使用了$on监听事件，此代码可以注释掉
            this.$emit('on-change',this.selections[this.nowIndex]);//子组件传递给父组件,带有参数
        }
    },
    mounted(){
        //监听事件
        eventBus.$on('reset-component',()=>{
            //回调函数处理
            console.log('$on事件的监听'); //点击不停的调用此事件，所以冒泡了，通过阻止冒泡事件
            this.isDrop = false;
        })
    }
}
</script>

<style scoped>
.selection-component{position:relative;display:inline-block}
.selection-show{border:1px solid #e3e3e3;padding:0 20px 0 10px;display:inline-block;position:relative;cursor:pointer;height:25px;line-height:25px;border-radius:3px;background:#fff}
.selection-show .arrow{display:inline-block;border-left:4px solid transparent;border-right:4px solid transparent;border-top:5px solid #e3e3e3;width:0;height:0;margin-top:-1px;margin-left:6px;margin-right:-14px;vertical-align:middle}
.selection-list{display:inline-block;position:absolute;left:0;top:25px;width:100%;background:#fff;border-top:1px solid #e3e3e3;border-bottom:1px solid #e3e3e3;z-index:5}
.selection-list li{padding:5px 15px 5px 10px;border-left:1px solid #e3e3e3;border-right:1px solid #e3e3e3;cursor:pointer;background:#fff;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.selection-list li:hover{background:#e3e3e3}
</style>
